<template>
  <div class="container">
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px" size="mini" class="ruleForm">
      <el-form-item label="姓名" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="ruleForm.idCard"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="sexCode">
        <el-select placeholder="性别" v-model="ruleForm.sexCode" @change="sexclick">
          <el-option :value="2" label="女"></el-option>
          <el-option :value="1" label="男"></el-option>
        </el-select>

      </el-form-item>
      <el-form-item label="户籍地" prop="domicilePlaceCode">
        <el-cascader ref="cascaderAddr" :options="workArea" :props="{value:'code',label:'name',children:'childVo'}"
          :show-all-levels="false" v-model="ruleForm.domicilePlaceCode" placeholder="请选择户籍地"
          @change="domicilePlaceclick"></el-cascader>
      </el-form-item>
      <el-form-item label="户籍地地址" prop="domicilePlaceAddress">
        <el-input v-model="ruleForm.domicilePlaceAddress"></el-input>
      </el-form-item>
      <el-form-item label="现居住地" prop="currentResidenceCode">
        <el-cascader ref="cascaderResidence" :options="workArea" :props="{value:'code',label:'name',children:'childVo'}"
          :show-all-levels="false" v-model="ruleForm.currentResidenceCode" placeholder="请选择户籍地"
          @change="currentResidenceclick"></el-cascader>
      </el-form-item>
      <el-form-item label="现居地地址" prop="currentResidenceAddress">
        <el-input v-model="ruleForm.currentResidenceAddress"></el-input>
      </el-form-item>
      <el-form-item label="工作经验" prop="workExp">
        <el-input v-model.number="ruleForm.workExp" style="width: 90%"></el-input>年
      </el-form-item>
      <el-form-item label="联系电话" prop="phone">
        <el-input v-model.trim="ruleForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" prop="mail">
        <el-input v-model.trim="ruleForm.mail"></el-input>
      </el-form-item>
      <el-form-item label="参加工作时间" required prop="workTime">

        <el-date-picker v-model="ruleForm.workTime" type="date" value-format="yyyy-MM-dd" placeholder="开始日期">
        </el-date-picker>

      </el-form-item>
      <el-form-item label="学历" prop="educationCode" class="address">
        <!-- <XLSelect :value="ruleForm.educationCode" @parentEvent="getXLChild" ref="XLDome"></XLSelect> -->
        <el-select v-model="ruleForm.educationCode" placeholder="请选择学历" @change="educationclick">
          <el-option v-for="item in optionList" :label="item.name" :value="item.val" :key="item.val"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="毕业院校" prop="graduateCollege">
        <el-input v-model="ruleForm.graduateCollege"></el-input>
      </el-form-item>
      <el-form-item label="技能及特长" prop="skillsSpecialties">
        <el-input v-model="ruleForm.skillsSpecialties"></el-input>
      </el-form-item>

      <el-form-item label="期望行业" prop="trade">
        <!-- <HYSelect :value="ruleForm.tradeText" @parentEvent="getHYChild" ref="HYDome"></HYSelect> -->
        <el-cascader ref="HYDome" v-model="ruleForm.trade" :options="options.trade" @change="tradeclick"
          :props="{value:'code', label:'name',children:'childVo',checkStrictly:true}" :show-all-levels="true"
          placeholder='请选择行业'>
        </el-cascader>
      </el-form-item>

      <el-form-item label="期望待遇" prop="hopeSalary">
        <el-input v-model.number="ruleForm.hopeSalary"></el-input>
      </el-form-item>
      <el-form-item label="专业" prop="majorCategory">
        <el-cascader ref="cascadermajor" :options="majorlist"
          :props="{value:'code',label:'name',children:'childVo',checkStrictly:true}" :show-all-levels="false"
          v-model="ruleForm.majorCategory" placeholder="请选择专业" @change="majorCateclick">
        </el-cascader>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" :loading="isloading" @click="submitForm('ruleForm')">确定</el-button>
        <el-button @click="resetForm('ruleForm')">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { prFindall, mcFindall, insert, loseJobDetail, update } from '../../../api/personal';
import { phoneValue } from '@/components/common/validate'
import { education } from '../../../api/jobList.js'
import { findTradeDict } from '../../../api/index.js';
//定义一个全局的变量
var validPhone = (rule, value, callback) => {
  //  else if (!isvalidPhone(value)) {
  //   callback(new Error('请输入正确的11位手机号码'))
  // }
  if (!value) {
    callback(new Error('请输入电话号码'))
  } else if (!phoneValue(value)) {
    callback(new Error('请输入正确的电话号码!'))
  } else {
    callback()
  }
}
export default {
  name: 'addJobFair',
  components: {

  },
  data () {
    return {
      dialogMap: false,
      // 禁止多次提交
      isloading: false,
      // 市场下拉框
      optionsData: '',
      separatorTime: '',
      holdstartDate: '',
      holdstartDateTwo: '',
      optionList: "",
      options: {
        trade: []
      },
      workArea: [],
      majorlist: [],
      ruleForm: {
        name: "",//姓名
        sex: "",//性别
        idCard: "",//身份证
        sexCode: "",//性别编码
        domicilePlace: "",//户籍地
        domicilePlaceCode: "",//户籍地编码
        currentResidence: "",//现居地
        currentResidenceCode: '',//现居地编码
        workExp: "",//工作经验
        phone: "",//手机号
        mail: "",//邮箱
        workTime: "",//参加工作时间
        education: "",//学历
        educationCode: "",//学历编码
        graduateCollege: "",//别业院校
        skillsSpecialties: "",//技能及特长
        trade: '',//期望行业编码
        tradeText: "",//期望行业
        hopeSalary: "",//期望待遇
        majorCategoryText: "",//专业
        majorCategory: "",//专业编码
        id: '',
        domicilePlaceAddress: "",//户籍地地址
        currentResidenceAddress: ''//常住地地址
      },
      rules: {

        name: [
          { required: true, message: '请填写姓名', trigger: 'blur' }
        ],
        sexCode: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        workTime: [
          { required: true, message: '请选择参加工作时间', trigger: 'change' }
        ],
        idCard: [
          { required: true, message: '请填写身份证', trigger: 'blur' },
          {
            pattern: /^[1-9]\d{5}(19|20)\d{2}[01]\d[0123]\d\d{3}[xX\d]$/,
            message: '请输入正确的身份证号',
            trigger: 'blur'
          }
        ],
        mail: [
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        workExp: [
          { required: true, message: '请填写工作经验', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' }
        ],
        currentResidenceCode: [
          { required: true, message: '请选择现居地', trigger: 'change' }
        ],
        // graduateCollege: [
        //   { required: true, message: '请填写毕业院校', trigger: 'blur' }
        // ],
        educationCode: [
          { required: true, message: '请选择学历', trigger: 'change' }
        ],
        // skillsSpecialties: [
        //   { required: true, message: '请填写技能和特长', trigger: 'blur' }
        // ],
        hopeSalary: [
          { required: true, message: '请填写期望待遇', trigger: 'blur' },
          { type: 'number', message: '必须为数字值' }
        ],
        trade: [
          { required: true, message: '请选择期望行业', trigger: 'change' }
        ],
        phone: [
          { required: true, trigger: 'blur', message: '请输入电话', },//这里需要用到全局变量
          { required: true, min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' },
          { validator: validPhone, trigger: 'blur' }
        ]
      }
    };
  },
  methods: {
    getLngLat (params) {
      console.log(params);
      this.ruleForm.lat = params.lat.toString();
      this.ruleForm.lng = params.lng.toString();
      console.log(this.ruleForm);
    },
    getDialogMap (params) {
      this.dialogMap = params;
    },
    // 选择时间
    holdTime (data) {
      this.ruleForm.holdTime = data;
    },
    // 验证是否有中文逗号
    contains (str, subStr, isIgnoreCase) {

      if (isIgnoreCase) {
        // 忽略大小写  
        str = str.toLowerCase();
        subStr = subStr.toLowerCase();
      }
      var startChar = subStr.substring(0, 1);
      var strLen = subStr.length;

      for (var j = 0; j < str.length - strLen + 1; j++) {
        if (str.charAt(j) == startChar) {
          /* 如果匹配起始字符,开始查找 */
          if (str.substring(j, j + strLen) == subStr) {
            /*如果从j开始的字符与 str 匹配 */
            return true;
          }
        }
      }
      return false;
    },
    //选择性别时触发
    sexclick (event) {
      console.log(event, "eventsex")
      if (event === 1) {
        this.ruleForm.sex = "男"
      } else {
        this.ruleForm.sex = "女"
      }
    },
    //选择户籍触发
    domicilePlaceclick (e, form, thsAreaCode) {
      console.log(e, "domicilePlaceclick")
      thsAreaCode = this.$refs['cascaderAddr'].getCheckedNodes()[0].pathLabels
      console.log(thsAreaCode, 'thsAreaCode')
      this.ruleForm.domicilePlace = thsAreaCode.join('-')
      this.ruleForm.domicilePlaceAddress = thsAreaCode.join('')
    },
    //选择现居地触发
    currentResidenceclick (e, form, thsAreaCode) {
      thsAreaCode = this.$refs['cascaderResidence'].getCheckedNodes()[0].pathLabels
      console.log(thsAreaCode, 'thsAreaCode')
      this.ruleForm.currentResidence = thsAreaCode.join('-')
      this.ruleForm.currentResidenceAddress = thsAreaCode.join('')
    },
    //选择学历触发
    educationclick (event) {
      let obj = {};
      obj = this.optionList.find((item) => {//这里的selectList就是上面遍历的数据源
        return item.val === event;//筛选出匹配数据
      });
      console.log(obj, 'obj')
      this.ruleForm.education = obj.name
    },
    //选择行业触发
    tradeclick (e, form, thsAreaCode) {
      this.$refs.HYDome.dropDownVisible = false;
      thsAreaCode = this.$refs['HYDome'].getCheckedNodes()[0].pathLabels
      console.log(thsAreaCode, 'thsAreaCode')
      this.ruleForm.tradeText = thsAreaCode.join('-')
    },
    //选择专业触发
    majorCateclick (e, form, thsAreaCode) {
      this.$refs.cascadermajor.dropDownVisible = false;
      thsAreaCode = this.$refs['cascadermajor'].getCheckedNodes()[0].pathLabels
      console.log(thsAreaCode, 'thsAreaCode')
      this.ruleForm.majorCategoryText = thsAreaCode.join('-')
    },
    // 添加成功
    submitForm (formName) {
      let that = this
      that.isloading = true
      const loading = that.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.2)'
      });

      that.$refs[formName].validate((valid) => {
        if (valid) {


          let parms = { ...this.ruleForm }

          parms.domicilePlaceCode = JSON.stringify(this.ruleForm.domicilePlaceCode)
          parms.currentResidenceCode = JSON.stringify(this.ruleForm.currentResidenceCode)
          parms.majorCategory = JSON.stringify(this.ruleForm.majorCategory)
          parms.trade = JSON.stringify(this.ruleForm.trade)
          if (this.ruleForm.id === '') {
            let now = new Date();
            let year = now.getFullYear(); //得到年份
            let month = now.getMonth();//得到月份
            let date = now.getDate();//得到日期
            let hour = now.getHours();//得到小时
            let minu = now.getMinutes();//得到分钟
            let sec = now.getSeconds();//得到秒
            month = month + 1;
            if (month < 10) month = "0" + month;
            if (date < 10) date = "0" + date;
            if (hour < 10) hour = "0" + hour;
            if (minu < 10) minu = "0" + minu;
            if (sec < 10) sec = "0" + sec;
            let timedata = year + "-" + month + "-" + date + " " + hour + ":" + minu + ":" + sec
            parms.createTime = timedata
            insert(parms).then(data => {
              loading.close();
              that.isloading = false
              if (data.success) {
                this.$router.push({
                  path: '/unemployed'
                })
              } else {
                this.rulezhlx()
                this.$message.error(`${data.msg}`);
              }
            });
          } else {
            update(parms).then(data => {
              loading.close();
              that.isloading = false
              if (data.success) {
                this.$router.push({
                  path: '/unemployed'
                })
              } else {
                this.rulezhlx()
                this.$message.error(`${data.msg}`);
              }
            });
          }




        } else {
          console.log('error submit!!');
          loading.close();
          that.isloading = false
          return false;
        }
      });
    },
    init () {
      this.prFindall()
      this.mcFindall()
      this.getOptionList()
      this.getOptionhyList()
    },
    //获取省市区
    prFindall () {
      prFindall().then(data => {
        if (data.success) {
          this.workArea = data.data
        }
      });
    },
    /**
* 获取学历信息
*/
    getOptionList () {
      education().then(res => {
        if (res.success) {
          this.optionList = res.data || []
        } else {
          this.$message.error(`${res.msg}`)
        }
      })
    },
    /**
 * 获取行业的下拉数据
 */
    getOptionhyList () {
      // 获取行业信息
      findTradeDict().then(res => {
        if (res.success) {
          this.options.trade = res.data;
        } else {
          this.$message.error(`${res.msg}`)
        }
      })

    },
    //获取专业
    mcFindall () {
      mcFindall().then(data => {
        if (data.success) {
          this.majorlist = data.data
        }
      });
    },
    // 取消
    resetForm (formName) {
      this.$router.go(-1)
    },
    // 获取子组件传过来的当前学历值
    getXLChild (cValue) {
      // 接收子组件传过来的值
      this.searchForm.education = cValue
    },
    // 获取子组件传过来的当前行业值
    getHYChild (cValue) {
      // 接收子组件传过来的值
      this.searchForm.trade = cValue;
    },
    rulezhlx () {
      this.ruleForm.domicilePlaceCode = JSON.parse(this.ruleForm.domicilePlaceCode)
      this.ruleForm.currentResidenceCode = JSON.parse(this.ruleForm.currentResidenceCode)
      this.ruleForm.majorCategory = JSON.parse(this.ruleForm.majorCategory)
      this.ruleForm.trade = JSON.parse(this.ruleForm.trade)
    },
    getDetail () {
      loseJobDetail(this.$route.query.id).then(data => {
        if (data.success) {
          this.ruleForm = data.data || {};
          this.rulezhlx()
        } else {
          this.$message.error(`${data.msg}`);
        }
      });
    },

  },
  mounted () {
    //  初始化加载数据
    this.$refs['ruleForm'].resetFields();
    this.init()
    if (this.$route.query.id) {
      this.getDetail()
    }

  },
  created () {
    // this.$refs['ruleForm'].resetFields();
    // this.init()
    // if (this.$route.query.id) {
    //   this.getDetail()
    // }

  },
  watch: {
    '$route': function (val, oldVal) {
      console.log(val, 'val')
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
      })
    },
    '$route.query.id': function (val, oldVal) {
      console.log(val, 'val')
      this.$nextTick(() => {
        this.$refs['ruleForm'].resetFields();
        this.getDetail();
      })
    }
  },
}
</script>

<style scoped>
.ruleForm {
    width: 30%;
}
.grid-content-map {
    width: 435px;
    height: 200px;
    background: indianred;
}
/* .address {
    margin-bottom: 40px;
} */
.dialog {
    height: 600px;
}
.dialog /deep/ .el-dialog__header {
    font-size: 14px;
    padding: 10px 0 5px 10px;
}
.dialog /deep/ .el-dialog__body {
    width: 100%;
    padding: 0;
    height: 100%;
}
.address /deep/ .el-button {
    position: absolute;
    top: 40px;
    left: 0;
}
</style>